<template>
  <div class="live-management">
    <div class="header">
      <h2>라이브 관리</h2>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        라이브 방 생성
      </el-button>
    </div>

    <!-- 直播间列表 -->
    <el-table :data="liveRooms" v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="커버" width="120">
        <template #default="{ row }">
          <img
            v-if="row.coverUrl"
            :src="`${API_BASE}${row.coverUrl}`"
            style="width: 80px; height: 45px; object-fit: cover; border-radius: 4px;"
            alt="커버"
          />
          <span v-else class="no-cover">커버 없음</span>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="제목" min-width="200" />
      <el-table-column prop="channel.name" label="채널" width="150" />
      <el-table-column label="연결된 비디오" width="200">
        <template #default="{ row }">
          <span v-if="row.replayVideo">{{ row.replayVideo.title }}</span>
          <span v-else class="no-video">비디오 연결 안됨</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="상태" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
            {{ row.status === 'active' ? '활성' : '비활성' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="manualViewerCount" label="수동 시청자 수" width="120">
        <template #default="{ row }">
          <span>{{ row.manualViewerCount || 0 }}명</span>
        </template>
      </el-table-column>
      <el-table-column label="미리 설정된 메시지" width="120">
        <template #default="{ row }">
          <span>{{ row.presets?.length || 0 }}개</span>
        </template>
      </el-table-column>
      <el-table-column prop="startedAt" label="생성 시간" width="180">
        <template #default="{ row }">
          {{ formatDate(row.startedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="작업" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="editLiveRoom(row)">편집</el-button>
          <el-button size="small" @click="managePresets(row)">메시지 관리</el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteLiveRoom(row)"
            :loading="row.deleting"
          >
            삭제
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchLiveRooms"
        @current-change="fetchLiveRooms"
      />
    </div>

    <!-- 创建/编辑直播间对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingRoom ? '라이브 방 편집' : '라이브 방 생성'"
      width="600px"
    >
      <el-form :model="roomForm" label-width="80px">
        <el-form-item label="제목" required>
          <el-input v-model="roomForm.title" placeholder="라이브 방 제목을 입력하세요" />
        </el-form-item>
        <el-form-item label="채널" required>
          <el-select v-model="roomForm.channelId" placeholder="채널을 선택하세요" style="width: 100%" @change="onChannelChange">
            <el-option
              v-for="channel in channels"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="연결된 비디오">
          <el-select v-model="roomForm.replayVideoId" placeholder="비디오를 선택하세요" style="width: 100%" clearable @visible-change="(v:boolean)=>{ if(v) fetchVideos() }">
            <el-option
              v-for="video in videos"
              :key="video.id"
              :label="video.title"
              :value="video.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="커버">
          <div style="display:flex; gap:12px; align-items:center; width:100%">
            <el-upload
              :action="`${API_BASE}/api/admin/uploads/cover`"
              name="cover-upload"
              :with-credentials="true"
              :show-file-list="false"
              :on-success="(res:any)=>{ if(res?.coverUrl){ roomForm.coverUrl = res.coverUrl } }"
            >
              <img v-if="roomForm.coverUrl" :src="`${API_BASE}${roomForm.coverUrl}`" style="width:120px;height:68px;object-fit:cover;border-radius:6px;" />
              <el-button v-else type="primary">커버 업로드</el-button>
            </el-upload>
            <el-input v-model="roomForm.coverUrl" placeholder="이미지 URL을 직접 입력할 수도 있습니다 (선택사항)" />
          </div>
        </el-form-item>
        <el-form-item label="수동 시청자 수">
          <el-input-number
            v-model="roomForm.manualViewerCount"
            :min="0"
            :max="999999999"
            placeholder="시청자 수를 입력하세요"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="상태" v-if="editingRoom">
          <el-select v-model="roomForm.status" style="width: 100%">
            <el-option label="활성" value="active" />
            <el-option label="비활성" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">취소</el-button>
        <el-button
          type="primary"
          @click="saveLiveRoom"
          :loading="saving"
          :disabled="!canSave"
        >
          {{ editingRoom ? '저장' : '생성' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 미리 설정된 메시지 관리 대화상자 -->
    <el-dialog v-model="showPresetsDialog" title="미리 설정된 메시지 관리" width="800px">
      <div class="presets-header">
        <el-button type="primary" size="small" @click="addPreset">
          <el-icon><Plus /></el-icon>
          메시지 추가
        </el-button>
      </div>

      <el-table :data="presets" style="width: 100%">
        <el-table-column prop="sortOrder" label="순서" width="80" />
        <el-table-column prop="content" label="메시지 내용" min-width="300">
          <template #default="{ row }">
            <el-input
              v-if="row.editing"
              v-model="row.content"
              @blur="savePreset(row)"
              @keyup.enter="savePreset(row)"
            />
            <span v-else>{{ row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isActive" label="상태" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.isActive"
              @change="savePreset(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="작업" width="150">
          <template #default="{ row }">
            <el-button
              v-if="!row.editing"
              size="small"
              @click="row.editing = true"
            >
              편집
            </el-button>
            <el-button
              v-else
              size="small"
              type="primary"
              @click="savePreset(row)"
            >
              저장
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deletePreset(row)"
            >
              삭제
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

const API_BASE = (import.meta as any)?.env?.VITE_API_BASE_URL || ''


// 响应式数据
const loading = ref(false)
const liveRooms = ref<any[]>([])
const channels = ref<any[]>([])
const videos = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const showCreateDialog = ref(false)
const showPresetsDialog = ref(false)
const saving = ref(false)
const editingRoom = ref<any>(null)
const currentRoom = ref<any>(null)

const roomForm = ref({
  title: '',
  channelId: '',
  replayVideoId: '',
  coverUrl: '',
  manualViewerCount: 0,
  status: 'active'
})

const presets = ref<any[]>([])

// 计算属性
const canSave = computed(() => {
  return roomForm.value.title && roomForm.value.channelId
})

// 方法
const fetchLiveRooms = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/admin/live-rooms', {
      params: {
        page: currentPage.value,
        limit: pageSize.value
      }
    })
    liveRooms.value = response.data.liveRooms
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('라이브 방 목록 가져오기 실패')
  } finally {
    loading.value = false
  }
}

const fetchChannels = async () => {
  try {
    const resp = await request.get('/api/admin/channels', { params: { limit: 200 } })
    channels.value = resp.data.channels
  } catch (error) {
    ElMessage.error('获取频道列表失败')
  }
}

const fetchVideos = async () => {
  try {
    const params: any = { limit: 200 }
    if (roomForm.value.channelId) params.channelId = roomForm.value.channelId
    const response = await request.get('/api/admin/videos', { params })
    videos.value = response.data.videos
  } catch (error) {
    ElMessage.error('获取视频列表失败')
  }
}

const onChannelChange = async () => {
  // 切换频道时，清空已选视频，重新拉取该频道下视频
  roomForm.value.replayVideoId = ''
  await fetchVideos()
}

const editLiveRoom = (room: any) => {
  editingRoom.value = room
  roomForm.value = {
    title: room.title || '',
    channelId: room.channelId,
    replayVideoId: room.replayVideoId || '',
    coverUrl: room.coverUrl || '',
    manualViewerCount: room.manualViewerCount || 0,
    status: room.status
  }
  showCreateDialog.value = true
  // 编辑模式下也按频道过滤可选视频
  fetchVideos()
}

const saveLiveRoom = async () => {
  if (!canSave.value) return

  saving.value = true
  try {
    if (editingRoom.value) {
      // 更新
      await request.put(`/api/admin/live-rooms/${editingRoom.value.id}`, roomForm.value)
      ElMessage.success('更新成功')
    } else {
      // 创建
      await request.post('/api/admin/live-rooms', roomForm.value)
      ElMessage.success('创建成功')
    }

    showCreateDialog.value = false
    resetRoomForm()
    fetchLiveRooms()
  } catch (error) {
    ElMessage.error(editingRoom.value ? '更新失败' : '创建失败')
  } finally {
    saving.value = false
  }
}

const deleteLiveRoom = async (room: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个直播间吗？', '确认删除', {
      type: 'warning'
    })

    room.deleting = true
    await request.delete(`/api/admin/live-rooms/${room.id}`)
    ElMessage.success('删除成功')
    fetchLiveRooms()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  } finally {
    room.deleting = false
  }
}

const managePresets = async (room: any) => {
  currentRoom.value = room
  try {
    const response = await request.get(`/api/admin/live-rooms/${room.id}/presets`)
    presets.value = response.data.presets.map((p: any) => ({ ...p, editing: false }))
    showPresetsDialog.value = true
  } catch (error) {
    ElMessage.error('获取预设消息失败')
  }
}

const addPreset = () => {
  presets.value.push({
    id: null,
    content: '新消息',
    sortOrder: presets.value.length,
    isActive: true,
    editing: true
  })
}

const savePreset = async (preset: any) => {
  try {
    if (preset.id) {
      // 更新
      await request.put(`/api/admin/live-rooms/${currentRoom.value.id}/presets/${preset.id}`, {
        content: preset.content,
        sortOrder: preset.sortOrder,
        isActive: preset.isActive
      })
    } else {
      // 创建
      const response = await request.post(`/api/admin/live-rooms/${currentRoom.value.id}/presets`, {
        content: preset.content,
        sortOrder: preset.sortOrder
      })
      preset.id = response.data.id
    }
    preset.editing = false
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const deletePreset = async (preset: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '确认删除', {
      type: 'warning'
    })

    if (preset.id) {
      await request.delete(`/api/admin/live-rooms/${currentRoom.value.id}/presets/${preset.id}`)
    }

    const index = presets.value.indexOf(preset)
    presets.value.splice(index, 1)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const resetRoomForm = () => {
  editingRoom.value = null
  roomForm.value = {
    title: '',
    channelId: '',
    replayVideoId: '',
    coverUrl: '',
    manualViewerCount: 0,
    status: 'active'
  }
  // 重要：重置对话框相关状态，避免“创建变编辑”的串状态
  showCreateDialog.value = false
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchLiveRooms()
  fetchChannels()
  fetchVideos()
})
</script>

<style scoped>
.live-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.no-cover, .no-video {
  color: #999;
  font-size: 12px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.presets-header {
  margin-bottom: 16px;
}
</style>
